<?php

namespace App\Http\Controllers;

use App\Libs\Response;
use Illuminate\Http\Request;
use Zipper;
use DB;

class Index extends Controller
{
    const MAX_SIZE = 100;

    private $allowExt = ['zip'];

    public function view()
    {
        return view('index');
    }

    public function publishAxure(Request $request)
    {
        ini_set('max_execution_time',0);
        set_time_limit(0);
        $projectName = htmlentities($request->input('project_name', ''), ENT_QUOTES, 'UTF-8');
        if (empty($projectName)) {
            return Response::fail('缺少参数');
        }
        $file = $request->file('file');
        if (!$request->hasFile('file')) {
            return Response::fail('请选择要上传的文件');
        }
        $fileName = $file->getClientOriginalName();
        if (!$file->isValid()) {
            return Response::fail('上传文件出错');
        }
        $size = ($file->getSize()) / 1024 / 1024; //上传的文件大小
        if ($size > self::MAX_SIZE) {
            return Response::fail(sprintf("最大只能上传%sM的文件", self::MAX_SIZE));
        }

        $ext = $file->extension(); //文件mime类型
        if (!in_array($ext, $this->allowExt)) {
            return Response::fail('不允许上传的文件类型！');
        }
        $uniquePath = sprintf("%s-%s", date('YmdHis'), $this->genUid());

        Zipper::make($file)->extractTo(sprintf("axure/%s", $uniquePath));
        $fileName = pathinfo($fileName, PATHINFO_FILENAME);
        $serverPath = public_path() . '/axure/' . $uniquePath;

        $fileArr = glob($serverPath.'/*');
        $dirCount = 0;
        foreach($fileArr as $k=>$v){
            if(is_dir($v)){
                $dirCount++;
            }
        }
        if($dirCount == 1){
            $cmd = sprintf("mv %s/* %s/", $serverPath . '/' . $fileArr[0], $serverPath);
            system($cmd);
        }

        DB::table('publish_log')->insert([
            'project_name' => $projectName,
            'save_path' => $serverPath,
            'visit_url' => trim(env('APP_URL', '/')) . '/axure/' . $uniquePath,
            'create_time' => date('Y-m-d H:i:s')
        ]);
        return Response::succ('发布成功');
    }

    public function axureList(Request $request)
    {
        $search = $request->input('search', '');
        $per_page = (int)$request->input('per_page', 0);
        $q = DB::table('publish_log')->where('is_del',0)->select('*')->orderBy('id', 'desc');
        if (!empty($search)) {
            $q->where('project_name', 'like', '%' . $search . '%');
        }
        if (!empty($per_page)) {
            $data = $q->paginate($per_page);
        } else {
            $data = $q->get();
        }
        return Response::succ($data);
    }

    public function genUid()
    {
        do {
            $uid = str_replace('.', '0', uniqid(rand(0, 999999999), true));
        } while (strlen($uid) != 32);
        return $uid;
    }

    public function del(Request $request)
    {
        $id = (int)$request->input('id',0);
        $data = DB::table('publish_log')->where('id',$id)->first();
        if(!isset($data->id)){
            return Response::fail('无效的id');
        }
        DB::table('publish_log')->where('id',$id)->update([
            'is_del' => 1
        ]);
        return Response::succ('删除成功');
    }

    public function removeDir($dirName)
    {
        if (!is_dir($dirName)) {
            return false;
        }
        $handle = @opendir($dirName);
        while (($file = @readdir($handle)) !== false) {
            if ($file != '.' && $file != '..') {
                $dir = $dirName . '/' . $file;
                is_dir($dir) ? $this->removeDir($dir) : @unlink($dir);
            }
        }
        closedir($handle);
        return rmdir($dirName);
    }
}
